<?php
namespace App\Http\Services;

class FaceService
{
    const SecretId  = "AKIDDgspWxCSmdDWYJn9G6j47tpbLs83mFZ5";
    const SecretKey = "Zt7Gfx95viIbOuLYXXJn0wpujGkxtWrw";
    const Url       = "https://iai.tencentcloudapi.com";

    //算法
    const Algo                  = "sha256";
    //规范请求串
    const HTTPRequestMethod     = "POST";
    const CanonicalURI          = "/";
    const CanonicalQueryString  = "";
    const CanonicalHeaders      = "content-type:application/json; charset=utf-8\nhost:iai.tencentcloudapi.com\n";
    const SignedHeaders         = "content-type;host";//参与签名的头部信息

    //签名字符串
    const Algorithm             = "TC3-HMAC-SHA256";
    const Service               = "iai";
    const Stop                  = "tc3_request";

    //接入区域
    const Region                = "ap-nanjing";
    //算法版本
    const Version               = "2020-03-03";


     //单个用户更新
    function update_member_avatar_width($url){
        return $this->DetectFaceAttributes($url.'?imageMogr2/scrop/500x500/crop/500x500/gravity/center');
    }

    /**
     * 示例
     * @return array
     */
    function DetectFaceAttributes($url){
        $param = [
            'Url' =>  $url,
            'FaceModelVersion' =>  "3.0",
        ];
        return $this->getCommonPostRequest("DetectFaceAttributes", $param, self::Version);
    }

    /**
     * 鉴权
     * @param string $action 方法
     * @param array  $param  参数
     * @param string $version 版本号
     * @return array
     */
    function getCommonPostRequest( $action, array $param = [], $version)
    {
        //时间戳
        $timeStamp  = time();
        //参数转化Json
        $paramJson  = json_encode($param);
        //规范请求串
        $hashedRequestPayload   =   $this->HashEncryption($paramJson);
        //echo $hashedRequestPayload . "\n";
        $canonicalRequest       =   self::HTTPRequestMethod . "\n" .
            self::CanonicalURI . "\n" .
            self::CanonicalQueryString . "\n" .
            self::CanonicalHeaders . "\n" .
            self::SignedHeaders . "\n" .
            $hashedRequestPayload;
        //签名字符串
        $date                   =   gmdate("Y-m-d", $timeStamp);//UTC 0时区的值
        $credentialScope        =   $date . "/". self::Service . "/". self::Stop;
        $hashedCanonicalRequest =   $this->HashEncryption($canonicalRequest);
        $stringToSign           =   self::Algorithm . "\n" .
            $timeStamp . "\n" .
            $credentialScope . "\n" .
            $hashedCanonicalRequest;

        //计算签名
        $secretDate             =   $this->HashHmacSha256Encryption($date,   'TC3' . self::SecretKey);
        $secretService          =   $this->HashHmacSha256Encryption(self::Service,   $secretDate);
        $secretSigning          =   $this->HashHmacSha256Encryption(self::Stop,  $secretService);

        //签名
        $signature              =   $this->HashHmacSha256Encryption($stringToSign,  $secretSigning, false);
        $authorization          =   self::Algorithm . ' ' .
            'Credential=' . self::SecretId . '/' . $credentialScope . ', ' .
            'SignedHeaders=' . self::SignedHeaders . ', ' .
            'Signature=' . $signature;
        //Header头部
        $headers = [
            "Authorization: $authorization",
            "Host: iai.tencentcloudapi.com",
            "Content-Type: application/json; charset=utf-8",
            "X-TC-Action: $action",
            "X-TC-Version: $version",
            "X-TC-Timestamp: $timeStamp",
            "X-TC-Region: ap-chengdu"
        ];
        //请求
        $response   = $this->get_curl_request(self::Url, $paramJson, self::HTTPRequestMethod, $headers);
        //解析
        if (!$response) {
            return ['code' => 0, 'codeError' => '1002', 'msg' => 'Interface request failed'];
        }
        $response = json_decode($response, true);
        if (!isset($response['Response'])) {
            return ['code' => 0, 'codeError' => '1003', 'msg' => 'Response error'];
        }


        if (isset($response['Response']['Error'])) {
            return [
                'code'          => 0
                , 'codeError'   => $response['Response']['Error']['Code']
                , 'msg'         => $response['Response']['Error']['Message']
                , 'RequestId'   => $response['Response']['RequestId']
            ];
        } else {
            return ['code' => 1, 'msg' => 'ok', 'data' => $response['Response']];
        }
    }

    function HashEncryption($sign){
        return strtolower(hash(self::Algo, $sign));
    }

    function HashHmacSha256Encryption($sign, $key, $flag = true){
        return hash_hmac(self::Algo, $sign, $key,  $flag);
    }

    /**
     * @param $url
     * @param array $param
     * @param string $mothod
     * @param array $headers
     * @param int $return_status
     * @param int $flag
     * @return array|bool|string
     */
    function get_curl_request($url, $param = [], $mothod = 'POST', $headers = [], $return_status = 0, $flag = 0)
    {
        $ch = curl_init();
        if (!$flag) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, 6);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (strtolower($mothod) == 'post') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        } else {
            $url = $url . "?" . http_build_query($param);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 2);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//        curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1"); //代理服务器地址
//        curl_setopt($ch, CURLOPT_PROXYPORT, 12639); //代理服务器端口
        $ret = curl_exec($ch);
        $code = curl_getinfo($ch);
        curl_close($ch);
        if ($return_status == "1") {
            return array($ret, $code);
        }
        return $ret;
    }
}
